<template>
  <div class="content">
    <div class="friend-wrapper">
      <!-- 搜索框 -->
      <div class="wrapper">
        <div class="search-wrapper">
          <input
            type="text"
            class="searchInput"
            v-model="search"
            @keydown="searchList"
            @keyup="change"
            placeholder="搜索"
          />
          <!-- <i class="icon iconfont icon-search"></i> -->
          <!-- <div class="searchInput-delete" v-show="haveText" @click="del"></div> -->
        </div>
        <div class="add_Plus" style="cursor: pointer" @click="createGroup"></div>
        <el-dialog title="创建群聊" :visible.sync="showAddmembers" width="300px">
          <div>
            <div style="display: flex; flex-direction: column">
              <el-input style="margin: 0 20px 20px 0" v-model="groupName" placeholder="请输入群名称"></el-input>
              <el-input v-model="description" placeholder="请输入群描述"></el-input>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancle">取 消</el-button>
            <el-button type="primary" @click="shure">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- <search></search> -->
      <!-- 信息 -->
      <chatlist v-show="sousuo" @open="drawer = true"></chatlist>
      <!-- 搜索列表 -->
      <div class="msglist"  v-show="sousuoList">
        <el-tabs>
          <ul class="msg">
            <li
              v-for="item in searchedChatlist"
              style="padding: 10px"
              :class="{ active: item.id === selectId }"
              @click="selectChatItem(item)"
              :key="item.id"
            >
              <el-badge :is-dot="item.newMessage" class="sessionlist">
                <div class="list-left">
                  <img
                    class="avatar"
                    width="42"
                    height="42"
                    style="display: block"
                    :alt="item.user.name"
                    :src="'http://im.wzhwgg.com:8070/wechatwebsite/images/default.png'"
                  />
                  <!-- <img class="avatar"  width="42" height="42" style="display: block" :alt="item.user.name" :src="'http://m.hhkj-life.com/wechatwebsite/' + item.user.img"> -->
                </div>
                <div class="list-right">
                  <p class="name">{{item.user.name}}</p>
                  <span class="time">{{item.messages[item.messages.length-1].date | time}}</span>
                  <p
                    class="lastmsg"
                    v-html="item.messages[item.messages.length-1].content"
                  >{{item.messages[item.messages.length-1].content}}</p>
                </div>
              </el-badge>
            </li>
          </ul>
        </el-tabs>
      </div>
      <!-- <chatlist></chatlist> -->
    </div>
    <el-drawer :visible.sync="drawer" v-model="direction" size="100%" v-if="showInPc">
      <div
        class="friendinfo"
        v-if="selectedChat"
        style="display: flex; flex-direction: column;justify-content: space-between; height: 100%;"
      >
        <message style="flex:1"></message>
        <v-text @send="send" style="width: 100%"></v-text>
      </div>
      <div class="nodata" @click="$router.push('/friend')" v-else>
        <div class="btn">请选择聊天对象</div>
      </div>
    </el-drawer>
    <div v-if="!showInPc" style="flex: 1;display: flex">
      <div
        class="friendinfo"
        v-if="selectedChat"
        style="display: flex; flex-direction: column;justify-content: space-between; height: 100%;"
      >
        <message style="flex:1"></message>
        <v-text @send="send" style="width: 100%"></v-text>
      </div>
      <div class="nodata" @click="$router.push('/friend')" v-else>
        <div class="btn">请选择聊天对象</div>
      </div>
    </div>
  </div>
</template>

<script>
import search from "../../components/search/search";
import chatlist from "../../components/chatlist/chatlist";
import message from "../../components/message/message";
import vText from "../../components/text/text";
import { mapState, mapGetters, mapActions } from "vuex";
import axios from "axios";
export default {
  components: {
    search,
    chatlist,
    message,
    vText
  },
  data() {
    return {
      showInPc: true,
      drawer: false,
      direction: "ltr",
      // wsUrl: 'ws://localhost:3000',
      // wsUrl: 'ws://221.224.9.154:7777/ws',
      wsUrl: "ws://221.224.9.154:15678/ws",
      lockReconnect: false,
      ws: null,
      showAddmembers: false,
      search: "",
      active: false,
      groupName: "",
      description: "",
      searchMessage: [],
      sousuo: true,
      sousuoList: false
    };
  },
  computed: {
    ...mapState([
      "selectId",
      "emojis",
      "user",
      "toMemberId",
      "model",
      "searchText",
      "chatGrouplist",
      "selectGroupId"
    ]),
    noText() {
      if (this.search === "") return true;
      return false;
    },
    haveText() {
      if (this.search === "") return false;
      return true;
    },
    ...mapGetters(["selectedChat","searchedChatlist"])
  },
  created() {
    //  console.log(this.searchedChatlist);
    this.fetchGroupChatlist();
    this.drawer = this.$route.query.open;
    this.showInPc = document.body.clientWidth < 420;
    if (this.ws) {
      this.ws.close(); // 关闭websocket连接
    }
    this.createWs();
  },
  methods: {
    ...mapActions(["selectSession", "selectGroupSession"]),
    selectChatItem(data) {
      // this.fetchMsgList()
      this.$emit("open");
      this.selectSession(data);
      this.readAllMessages();
    },
    selectGroupChatItem(data) {
      // this.fetchMsgList()
      this.$emit("open");
      this.selectGroupSession(data);
      this.readAllMessages();
    },
    readAllMessages() {
      boundAsync.callback(2, null).then(function(actualResult) {
        const expectedResult = true;
        assert.equal(
          expectedResult,
          actualResult,
          "notify client is " + expectedResult
        );
      });
    },
    fetchMsgList() {
      let params = new FormData();
      params.append("id", this.user.memberId);
      params.append("type", "member");
      params.append("pageNum", 1);
      params.append("pageSize", 10);
      // let params = {
      //     id: this.user.memberId,
      //     type: 'member',
      //     pageNum: 1,
      //     pageSize: 10
      // }
      this.$http.post("/api/mMessage/getHistoryMessage.do", params);
    },
    fetchmsgBox() {
      let params = new FormData();
      params.append("memberId", this.user.memberId);
      // params.append('id', this.user.memberId)
      // params.append('type', 'member')
      // params.append('pageNum', 1)
      // params.append('pageSize', 10)
      this.$http.post("/api/mMessage/msgBoxPage.do", params);
    },
    async fetchGroupChatlist() {
      const { data } = await this.$http.get(
        `/api/groupMessage/getGroupByUserId.do?memberId=${this.user.memberId}`
      );
      this.$store.dispatch("groupList", data.object);
    },
    change() {
      this.sousuo = true;
      this.sousuoList = false;
      this.$store.dispatch("search", this.search);
    },
    searchList(e) {
      var params = new FormData();
      params.append("name", this.search);
      params.append("memberId", this.$store.state.user.memberId);
      if (e.keyCode == 13) {
        axios
          .post(
            "http://im.wzhwgg.com:8070/wechatwebsite/index/getmembers.do",
            params
          )
          .then(res => {
            console.log(res.data.object);
            if (res.data.object.length <= 0) {
              this.sousuo = true;
              this.sousuoList = false;
            } else {
              this.sousuo = false;
              this.sousuoList = true;
              this.searchMessage = res.data.object;
            }
          });
      }
    },
    del() {
      this.search = "";
      this.change();
    },
    createGroup() {
      this.showAddmembers = true;
    },
    async shure() {
      let that = this;
      let params = new FormData();
      params.append("memberId", this.user.memberId);
      params.append("groupName", this.groupName);
      params.append("description ", this.description);

      const { data: object } = await this.$http.post(
        `/api/group/add.do`,
        params
      );
      // this.$http.post(`/api/group/add.do?memberId=${this.user.memberId}&groupName=${this.groupName}&description=${this.description}`, params)
      this.fetchGroupChatlist();
      this.showAddmembers = false;
    },

    async fetchGroupChatlist() {
      const { data } = await this.$http.get(
        `/api/groupMessage/getGroupByUserId.do?memberId=${this.user.memberId}`
      );
      this.$store.dispatch("groupList", data.object);
    },
    cancle() {
      this.showAddmembers = false;
    },
    send(content) {
      // this.ws.send(JSON.stringify(content));
      this.ws.send(JSON.stringify(content));
    },
    createWs() {
      try {
        if (typeof WebSocket === "undefined") {
          this.$message("您的端口不支持WebSocket");
          return false;
        }
        this.ws = new WebSocket(this.wsUrl);
        this.initWs();
      } catch (e) {
        console.log(e, 111111);

        this.reconnect(this.wsUrl);
      }
    },
    initWs() {
      let that = this;
      this.ws.onopen = function(e) {
        // that.$message('链接服务器成功');
        // that.ws.send(JSON.stringify({
        //       "content":"online",
        //       "userId": `${that.user.memberId}`,
        //       "to":{
        //       "type":"status"
        //       }
        //     }
        //   )
        // );
        that.ws.send(
          JSON.stringify({
            content: `online`,
            memberId: `${that.user.memberId}`,
            to: {
              type: "status"
            }
          })
        );
        // console.log(`上线人: ${that.user.memberId}`);

        that.keepAlive();
        // ws.send(this.content);
      };

      that.ws.onclose = function(e) {
        // console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
        // that.$message('服务器关闭');
        that.reconnect(that.wsUrl);
      };

      that.ws.onerror = function() {
        that.$message("服务器出错");
        that.reconnect(that.wsUrl);
      };

      that.ws.onmessage = function(e) {
        console.log(e, "收到");

        let data = JSON.parse(e.data);
        if (data && data.type == "friend") {
          this.$store.commit("selectFriend", {
            id: data.id,
            realName: data.username,
            status: "offline",
            sign: null,
            avatar: data.avatar,
            weixinId: null,
            gender: null,
            remark: ""
          });
          if (data.id) {
            this.$message("收到好友信息");
            this.$store.dispatch("send");
            var msg = {
              type: data.type,
              content: data.content == "offline" ? "下线！" : data.content,
              flag: false
            };

            this.hasNewMessage();
            this.$store.dispatch("sendMessage", msg);
          }
        } else {
          if (data.id) {
            this.$message("收到群信息");
            // this.$store.dispatch('send')
            var msg = {
              id: data.id,
              type: data.type,
              username: data.username,
              content: data.content == "offline" ? "下线！" : data.content,
              flag: false
            };
            this.$store.dispatch("sendMessage", msg);
            this.hasNewMessage();
          }
        }
      }.bind(this);

      window.onbeforeunload = function() {
        this.ws.close();
      };
    },
    hasNewMessage() {
      boundAsync.callback(1, null).then(function(actualResult) {
        const expectedResult = true;
        assert.equal(
          expectedResult,
          actualResult,
          "notify client is " + expectedResult
        );
      });
    },
    reconnect() {
      let that = this;
      console.log(that.lockReconnect);

      if (that.lockReconnect) return;
      that.lockReconnect = true;
      setTimeout(function() {
        //没连接上会一直重连，设置延迟避免请求过多
        that.createWs(that.wsUrl);
        that.lockReconnect = false;
      }, 2000);
    },
    keepAlive() {
      let obj = {
        to: {
          type: "ping"
        }
      };
      // setInterval(() => {
      //   this.ws.send(JSON.stringify(obj));
      //   console.log('ping');
      // }, 1000 * 30)
    }
  },
  destroyed() {
    this.ws.close();
  },
  filters: {
    // 将日期过滤为 hour:minutes
    time(date) {
      if (typeof date === "string") {
        date = new Date(date);
      }
      if (date.getMinutes() < 10) {
        return date.getHours() + ":0" + date.getMinutes();
      } else {
        return date.getHours() + ":" + date.getMinutes();
      }
    }
  }
};
</script>
<style lang="stylus" scoped>
.msglist {
  overflow-y: scroll;
  height: 100%;

  .sessionlist {
    display: flex;
    padding: 12px;
    transition: background-color 0.1s;
    font-size: 0;

    &:hover {
      background-color: rgb(220, 220, 220);
    }

    &.active {
      background-color: #c4c4c4;
    }

    .avatar {
      border-radius: 2px;
      margin-right: 12px;
    }

    .list-right {
      position: relative;
      flex: 1;
      margin-top: 4px;
    }

    .name {
      display: inline-block;
      vertical-align: top;
      font-size: 14px;
    }

    .time {
      float: right;
      color: #999;
      font-size: 10px;
      vertical-align: top;
    }

    .lastmsg {
      position: absolute;
      font-size: 12px;
      width: 130px;
      height: 15px;
      line-height: 15px;
      color: #999;
      bottom: 4px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
<style>
.el-tabs__header {
  padding: 0 20px !important;
}
</style>
<style lang="stylus" scoped>
.wrapper {
  background-color: rgb(230,230,230);
  position: relative;
  padding: 22px 12px 12px 12px;
}

.add_Plus {
    width: 16px;
  height: 16px;
  background-image : url("../../assets/images/add.jpg");
  background-size : 100% 100%;
  position: absolute;
  top: 26px;
  right: 12px;
}

.search-wrapper {
  position: relative;
  border-radius : 10px;
  display: flex;
  box-sizing: border-box;
  height: 26px;
  width: 90%;
  background-color: #e5e3e2;
  border: 1px solid #d9d7d6;
  border-radius: 2px;

  .searchInput {
    flex: 1;
    font-size: 12px;
    padding: 6px;
    background-color: rgb(213,217,220);
    outline: none;
    &:focus {
      background-color: #f2efee;
    }
  }

  .icon-search {
    display: inline-block;
    width: 24px;
    height: 24px;
    font-size: 14px;
    line-height: 24px;
    text-align: center;
  }

  .searchInput-delete {
    display: block;
    position: absolute;
    outline: none;
    top: 0;
    right: 0;
    width: 24px;
    height: 100%;
    background-image: url('../../components/search/delete.png');
    background-size: 26px;
    background-position: center;
    background-repeat: no-repeat;
    cursor: pointer;
  }
}
</style>
<style lang="stylus" scoped>
.content {
  display: flex;
  height: 100%;

  .friend-wrapper {
    width: 250px;
    height: 100%;
    background: rgb(230, 230, 230);
  }

  .friendinfo {
    flex: 1;
    align-items: flex-start;
    height: 500px;
  }
}
</style>
<style>
.nodata {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-image: url("../../assets/images/chat-bg.png");
  background-size: 100% 100%;
}
.nodata .btn {
  padding: 12px 30px;
  border-radius: 4px;
  font-size: 1.2rem;
  background: transparent;
  color: rgb(68,157,252);
  border: solid 1px rgb(68,157,252);
}
@media screen and (max-width: 720px) {
  .content .friend-wrapper {
    width: 100% !important;
    display: flex;
    flex-direction: column;
  }
}
</style>
